package com.gitee.hao.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitee.hao.entity.DyMaConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

import java.util.Base64;

import static com.gitee.hao.utils.HttpClientUtils.post;
import static com.gitee.hao.utils.HttpClientUtils.postReturnFile;


/**
 * @author hao
 */
@Slf4j
public class DyQrService {

    private DyMaConfig dyMaConfig;

    public void setDyMaConfig(DyMaConfig dyMaConfig) {
        this.dyMaConfig = dyMaConfig;
    }

    /**
     * @return access_token
     * @throws Exception
     */
    public String postToken() throws Exception {
        JSONObject paramJson = new JSONObject();
        paramJson.put("grant_type", "client_credential");
        paramJson.put("appid", this.dyMaConfig.getAppid());
        paramJson.put("secret", this.dyMaConfig.getSecret());
        String json = post("https://developer.toutiao.com/api/apps/v2/token",
            paramJson.toString(),
            "application/json",
            "UTF-8", 10000, 10000);
        final JSONObject data = (JSONObject) JSON.parseObject(json).get("data");
        return (String) data.get("access_token");
    }

    /**
     * 生成带参小程序二维码
     *
     * @param scene 参数
     * @param page  跳转页面
     */
    public File getDyQr(String scene, String page) throws Exception {
        final String accessToken = postToken();
        log.info("accessToken={}", accessToken);
        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("access_token", accessToken);
        paramJson.put("scene", scene);
        paramJson.put("path", page);
        paramJson.put("width", 430);
        paramJson.put("appname", "douyin");
//            paramJson.put("line_color", "{ \"r\": 0, \"g\": 0, \"b\": 0 }");
//            paramJson.put("background", "{ \"r\": 255, \"g\": 255, \"b\": 255 }");
        paramJson.put("set_icon", true);
        return postReturnFile("https://developer.toutiao.com/api/apps/qrcode",
            paramJson.toString(),
            "application/json",
            "UTF-8", 10000, 10000);

        //res = fileToBase64(file);
        //return res;
    }

    public static String fileToBase64(File file) {
        return Base64.getEncoder().encodeToString(fileToByte(file));
    }


    /**
     * 文件File类型转byte[]
     *
     * @param file
     * @return
     */
    public static byte[] fileToByte(File file) {
        byte[] fileBytes = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}